<template>
  <el-card shadow="hover" header="日程" v-auths="['schedule']">
    <el-button
      type="primary"
      icon="el-icon-plus"
      size="small"
      class="addButton"
      @click="openDialog()"
      >添加日程</el-button
    >
    <el-calendar v-model="date" ref="calendar">
      <template #header="{ date }">
        <span>{{ date }}</span>
        <el-button-group>
          <el-button size="small" @click="selectDate(date, 'prev-month')">
            上个月
          </el-button>
          <el-button size="small" @click="selectDate(date, 'today')"
            >今天</el-button
          >
          <el-button size="small" @click="selectDate(date, 'next-month')">
            下个月
          </el-button>
        </el-button-group>
      </template>
      <template #date-cell="{ data }">
        <div class="dateBox">
          <div class="topInfo">
            <p class="date">{{ data.day.split("-").slice(2).join("") }}</p>
          </div>
          <div class="plan" v-for="(list, key) in scheduleData" :key="key">
            <div v-if="key == data.day" class="list">
              <el-popover
                placement="right"
                :width="350"
                trigger="hover"
                v-for="(item, index) in list"
                :key="item.id"
                popper-class="detailForm"
                @show="showdetailForm(item)"
              >
                <template #reference>
                  <p>日程{{ index + 1 }}：{{ item.title }}</p>
                </template>
                <form
                  :model="detailForm"
                  ref="detailForm"
                  label-width="auto"
                  label-position="right"
                  class="planDetail"
                >
                  <el-form-item label="标题：">
                    <p>{{ detailForm.title }}</p>
                  </el-form-item>
                  <el-form-item label="地点：">
                    <p>{{ detailForm.address }}</p>
                  </el-form-item>
                  <el-form-item label="内容：">
                    <p>{{ detailForm.content }}</p>
                  </el-form-item>
                  <el-form-item label="开始时间：">
                    <p>{{ detailForm.startTime }}</p>
                  </el-form-item>
                  <el-form-item label="结束时间：">
                    <p>{{ detailForm.endTime }}</p>
                  </el-form-item>
                  <el-form-item label="参与人：">
                    <p>{{ detailForm.ownerAdminNames }}</p>
                  </el-form-item>
                  <el-form-item label="备注：">
                    <p>{{ detailForm.remark }}</p>
                  </el-form-item>
                </form>
              </el-popover>
            </div>
          </div>
        </div>
      </template>
    </el-calendar>
  </el-card>
  <!-- 添加日程 -->
  <el-dialog
    v-model="dialogVisible"
    title="添加日程"
    width="50%"
    destroy-on-close
    :before-close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="dialogForm"
      label-width="auto"
      label-position="right"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          clearable
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="地点" prop="address">
        <el-input
          v-model="form.address"
          clearable
          placeholder="请输入地点"
        ></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content" style="width: 100%">
        <el-input
          v-model="form.content"
          clearable
          placeholder="请输入内容"
          type="textarea"
          rows="3"
        ></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="请选择计划回款日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
          style="width: 100%"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="请选择计划回款日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
          style="width: 100%"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="参与人" prop="ownerAdminList">
        <el-select
          v-model="form.ownerAdminList"
          placeholder="请选择参与人"
          style="width: 100%"
          clearable
          multiple
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否提醒" prop="eventType" style="width: 100%">
        <el-switch
          v-model="form.eventType"
          :inactive-value="0"
          :active-value="1"
        />
      </el-form-item>
      <el-form-item
        label="提醒时间"
        prop="remindType"
        v-if="form.eventType == 1"
      >
        <el-select
          v-model="form.remindType"
          placeholder="请选择提醒时间"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in remindTypeList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="add" :loading="isSaveing">
          保 存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

 <script>
import { queryTypeByDic } from '@/utils/getData'
export default {
  name: 'schedule',
  title: "日程",
  icon: "el-icon-date",
  description: "日程信息展示",
  data () {
    return {
      date: new Date(),
      scheduleData: {},
      dialogVisible: false,
      isSaveing: false,
      form: {
        createAdminId: '',
        title: '',
        content: '',
        address: '',
        startTime: '',
        endTime: '',
        ownerAdminList: [],
        ownerAdminIds: [],//参与人用户id
        eventType: 0,//提醒状态：0不提醒 1提醒
        remindType: 0,//提醒时间：0准时提醒1：5分钟前2：15分钟前3：30分钟前4：一个小时前5：两个小时前6：一天前7：两天前8：一周前
      },
      detailForm: {},
      userList: [],
      remindTypeList: [],//提醒时间类型
      userInfo: '',
      //验证规则
      rules: {
        title: [
          { required: true, message: '请输入标题', }
        ],
        content: [
          { required: true, message: '请输入内容', }
        ],
        address: [
          { required: true, message: '请输入地点', }
        ],
        startTime: [
          {
            type: 'date',
            required: true,
            message: '请选择开始时间',
            trigger: 'change',
          },
        ],
        endTime: [
          {
            type: 'date',
            required: true,
            message: '请选择结束时间',
            trigger: 'change',
          },
        ],
      }
    }
  },
  beforeMount () {
    this.userInfo = this.$TOOL.data.get('USER_INFO')

  },
  mounted () {
    let day = new Date()
    let year = day.getFullYear()
    let month = +day.getMonth() + 1
    let time = `${year}-${month}`
    this.getScheduleList(time)
    this.getUserList()
    this.getType()
  },
  methods: {
    // 获取日程列表
    async getScheduleList (time) {
      let param = {
        adminId: this.userInfo.userId,
        time: time
      }
      let res = await this.$API.schedule.getScheduleList.get(param)
      console.log(res)
      this.scheduleData = res.data
    },

    // 获取用户
    async getUserList () {
      let param = {
        limit: 1000,
        page: 1
      }
      let { data } = await this.$API.user.getUserList.get(param)
      this.userList = data
    },
    // 获取提醒时间类型
    async getType () {
      let type = await queryTypeByDic('remindType')
      this.remindTypeList = type

    },

    openDialog () {
      let date = new Date()
      this.form.startTime = this.$TOOL.dateFormat(date, 'yyyy-MM-dd hh:mm:ss')
      this.dialogVisible = true
    },

    selectDate (date, val) {
      this.$refs.calendar.selectDate(val)
      let dateList = date.split(' ')
      let year = ''
      let month = ''
      let time = ''
      let day = new Date()
      switch (val) {
        case 'prev-month':
          year = dateList[0]
          month = +dateList[2] - 1
          if (month == 0) {
            month = 12
            year = +year - 1
          }
          time = `${year}-${month}`
          console.log(time)
          this.getScheduleList(time)
          break
        case 'today':
          year = day.getFullYear()
          month = +day.getMonth() + 1
          time = `${year}-${month}`
          this.getScheduleList(time)
          console.log(time)
          break
        case 'next-month':
          year = dateList[0]
          month = +dateList[2] + 1
          if (month == 13) {
            month = 1
            year = +year + 1
          }
          time = `${year}-${month}`
          this.getScheduleList(time)
          console.log(time)
          break
      }

    },

    //添加日程
    async add () {
      this.form.createAdminId = this.userInfo.userId
      this.form.ownerAdminIds = this.form.ownerAdminList.join(',')
      let data = { ...this.form }
      delete data.ownerAdminList
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          let res = await this.$API.schedule.addSchedule.post(data)
          this.isSaveing = false
          if (res.code == 200) {
            this.getScheduleList()
            this.$message.success("操作成功")
            this.handleClose()
          }
        }
      })
    },

    // 关闭弹窗
    handleClose () {
      this.$refs.dialogForm.resetFields()
      this.dialogVisible = false
    },

    // 显示日程安排详情
    showdetailForm (item) {
      console.log(item)
      let nameList = []
      let idList = item.ownerAdminIds.split(',')
      console.log(idList)
      this.userList.forEach(item => {
        idList.map(a_item => {
          if (item.id == +a_item) {
            nameList.push(item.username)
          }
        })
      })
      this.detailForm = item
      this.detailForm.ownerAdminNames = nameList.join(',')
    },
    // 设置就日期选择范围  今天之后
    disabledDate (time) {
      return time.getTime() < Date.now() - 8.64e7//如果没有后面的-8.64e7就是不可以选择
    },
  }
}
</script>
<style lang="scss" scoped>
.el-card {
  position: relative;
}
:deep(.el-calendar-day) {
  height: 150px;
}
.addButton {
  position: absolute;
  top: 20px;
  right: 40px;
}
.topInfo {
  .date {
    font-weight: 600;
  }
  .show {
    display: block;
  }
}
.plan {
  margin-top: 5px;
}
.list {
  max-height: 100px;
  overflow-y: auto;
  p {
    line-height: 2em;
  }
}
.detailForm {
  .el-form-item {
    margin-bottom: 0;
    :deep(.el-form-item__label) {
      color: #999;
    }
  }
}
</style>